package cn.zc.curriculum.service.service.impl;

import cn.hutool.core.codec.Base64Encoder;
import cn.tools.common.enums.TestedFile;
import cn.tools.core.VO.PageVO;
import cn.tools.core.exception.BizException;
import cn.tools.core.utils.mybatis.PageUtil;
import cn.zc.curriculum.entity.CurriculumImg;
import cn.zc.curriculum.entity.Dto.CurriculumImgDto;
import cn.zc.curriculum.entity.UploadFilePaths;
import cn.zc.curriculum.service.config.UploadConfig;
import cn.zc.curriculum.service.config.hander.VideoResourceHttpRequestHandler;
import cn.zc.curriculum.service.mapper.CurriculumImgMapper;
import cn.zc.curriculum.service.service.CurriculumImgService;
import cn.zc.curriculum.service.service.UploadFileService;
import cn.zc.curriculum.service.service.UploadFileServiceAsync;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author keno
 * @since 2022-02-17
 */
@Service
public class CurriculumImgServiceImpl extends ServiceImpl<CurriculumImgMapper, CurriculumImg> implements CurriculumImgService {
    @Resource
    private UploadConfig uploadConfig;

    @Resource
    private UploadFileService uploadFileService;

    @Resource
    private UploadFileServiceAsync uploadFileServiceAsync;

    @Resource
    private CurriculumImgMapper curriculumImgMapper;

    /**
     * 注入处理本地文件流配置类
     */
    @Resource
    private VideoResourceHttpRequestHandler videoResourceHttpRequestHandler;


    /**
     * 保存图片
     * @param image
     * @param imgType
     * @return
     */
    public String saveImgToData(MultipartFile image, String imgType)  {


        UploadFilePaths uploadFilePaths = uploadFileService.testedFile(image);
        for (String name:uploadConfig.getImgEnd()) {
            if(name.equals(uploadFilePaths.getEndName().toLowerCase())){
                try {
                    uploadFileService.uploadFileTestedCloud(image.getInputStream(),uploadFilePaths.getFileSavePath(),TestedFile.IMG);
                    uploadFileService.saveLocalTested(image.getInputStream(),uploadFilePaths.getFilePath() ,uploadFilePaths.getLocalPath(), TestedFile.IMG);
                }catch (Exception e){
                    e.printStackTrace();
                }
                CurriculumImg curriculumImg = new CurriculumImg();
                curriculumImg.setImgType(Integer.valueOf(imgType));
                //保存前先检查配置文件是否允许保存到对应点
                if(uploadConfig.isImgOssSave()) {
                    curriculumImg.setOssUrl(uploadFilePaths.getOssSavePath());
                }
                if(uploadConfig.isImgLocalSave()) {
                    curriculumImg.setImgUrl(uploadFilePaths.getLocalPath());
                }
                curriculumImg.setEndName(uploadFilePaths.getEndName());
                if(!save(curriculumImg)){
                    throw new BizException("保存图片失败");
                }
                return curriculumImg.getId();
            }

        }

        throw new BizException("上传失败，暂不支持此类型格式图片：" + uploadFilePaths.getEndName());

    }



    /**
     * 删除图片数据
     * @param id
     */
    @Override
    public void deleteCurriculumImg(String id) {
        CurriculumImg byId = getById(id);
        if(byId == null){
            throw new BizException("未查找到图片数据");
        }
        uploadFileServiceAsync.deleteOssFile(byId.getOssUrl());
        if(byId.getImgUrl() != null){
            uploadFileServiceAsync.deleteLocalFile(byId.getImgUrl());
        }
        if(!removeById(id)){
            throw new BizException("删除失败");
        }

    }


    /**
     * 根据id或者类型获取图片数据
     * @param pageVO
     * @param id
     * @param imgType
     * @return
     */
    @Override
    public List<CurriculumImgDto> getCurriculumImg(PageVO pageVO, String id, String imgType) {
        return curriculumImgMapper.getCurriculumImg(PageUtil.initPage(pageVO),id,imgType);

    }

    /**
     * base64形式返回图片
     * @param id
     * @return
     */
    @Override
    public String findLocalFileData(String id, HttpServletResponse response) {
        CurriculumImg imgInfo = getById(id);
        if(imgInfo == null){
            throw new BizException("数据库中没有此图片信息");
        }

        byte[] bytes = null;
        String base64Data = null;
        FileInputStream fileInputStream = null;
        try {
            File file = new File(imgInfo.getImgUrl());
            fileInputStream = new FileInputStream(file);
            int imgSize = fileInputStream.available();
            bytes = new byte[imgSize];
            fileInputStream.read(bytes);
            base64Data = Base64Encoder.encode(bytes);
            response.setHeader("Content-Type","image/" + imgInfo.getEndName());

        }catch (IOException e){
            e.printStackTrace();
            throw new BizException("本地未找到此图片，请确认本地是否存在此图片");
        }finally {
            if(fileInputStream != null){
                try {
                    fileInputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

        return base64Data;
    }


    /**
     * 流形式返回图片
     * @param request
     * @param response
     * @param imgId
     */
    @Override
    public void findImageStream(HttpServletRequest request, HttpServletResponse response, String imgId) {
        CurriculumImg imgInfo = getById(imgId);
        if(imgInfo.getImgUrl() != null) {
            videoResourceHttpRequestHandler.path = imgInfo.getImgUrl();
            response.setContentType("image/"+ imgInfo.getEndName());
            try {
                videoResourceHttpRequestHandler.handleRequest(request, response);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }else {
            throw new BizException("图片资源不存在，无法显示");
        }
    }


}
